import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 *用于补充mybatis generator 自动生成缺少的service和 impl层
 */

packageName = "com.sample;"
typeMapping = [
  (~/(?i)int/)                      : "long",
  (~/(?i)float|double|decimal|real/): "double",
  (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
  (~/(?i)date/)                     : "java.sql.Date",
  (~/(?i)time/)                     : "java.sql.Time",
  (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def className2 = javaName(table.getName(), false)
  def fields = calcFields(table)
  new File(dir, className + "Service.java").withPrintWriter { out -> generateService(out, className, fields,className2) }
  new File(dir, className + "ServiceImpl.java").withPrintWriter { out -> generateServiceImpl(out, className, fields,className2) }
}

def generateService(out, className, fields,className2) {
  out.println	"/**"
  out.println	        " * @Author: "
  out.println	        " * @Date: "
  out.println	        " * @Description:"
  out.println	        " */"
  out.println	        "public interface ${className}Service  extends BaseService<Long, ${className}Computer, " +
          "${className}Example, ${className}Mapper> {"
  out.println	        "}"

}
def generateServiceImpl(out, className, fields,className2) {
  out.println	"@Service"
  out.println	        "public class ${className}ServiceImpl implements ${className}Service {"
  out.println	        "    @Autowired"
  out.println	        "    private ${className}Mapper ${className2}Mapper;"
  out.println	        ""
  out.println	        "    @Override"
  out.println	        "    public ${className}Mapper getMapper() {"
  out.println	        "        return ${className2}Mapper;"
  out.println	        "    }"
  out.println	        "}"
}

def calcFields(table) {
  DasUtil.getColumns(table).reduce([]) { fields, col ->
    def spec = Case.LOWER.apply(col.getDataType().getSpecification())
    def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
    fields += [[
                 name : javaName(col.getName(), false),
                 type : typeStr,
                 comment: col.getComment(),
                 annos: ""]]
  }
}

def javaName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
    .collect { Case.LOWER.apply(it).capitalize() }
    .join("")
    .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}
